import { TypeDef } from "./type-def";

export class ListData<T> {
  code: number;
  msg: string;
  total = 0;
  dt: T[] = [];

  constructor(response: TypeDef.ResponseData, mapper: TypeDef.DataMapper) {
    this.total = response.data.total;
    this.code = response.code;
    this.msg = response.msg;

    response.data.dt.forEach(dt => {
      const data = {};
      Object.keys(mapper).forEach(key => (data[key] = dt[mapper[key]]));
      this.dt.push(data as T);
    });
  }
}

export class ListParams {
  private pageIndex: number;
  private pageSize: number;
  private dt: {
    [key: string]: any;
  };

  constructor(dt: { [key: string]: any } = {}, pageIndex = 1, pageSize = 10) {
    this.dt = dt;
    this.pageIndex = pageIndex;
    this.pageSize = pageSize;
  }

  setPageIndex(pageIndex: number) {
    this.pageIndex = pageIndex;
  }

  setPageSize(pageSize: number) {
    this.pageSize = pageSize;
  }

  addParam(key: string, value: any) {
    this.dt[key] = value;
  }

  addParams(params: TypeDef.RequestParam) {
    Object.keys(params).forEach(key => this.addParam(key, params[key]));
  }
}

export class ListRequestParams {
  dt: TypeDef.RequestParam;

  constructor(response: TypeDef.RequestParam, mapper: TypeDef.DataMapper) {
    const params = {};
    Object.keys(response).forEach(key => (params[mapper[key]] = response[key]));
    this.dt = params;
  }
}

export const ValidateRequired =  (validateForm: TypeDef.RequestParam) => {
  Object.keys(validateForm).forEach(key => {
    if (
      !validateForm[key].hasError("required") &&
      validateForm[key].value === null
    ) {
      validateForm[key].setErrors(null);
    } else {
      validateForm[key].markAsDirty();
      validateForm[key].updateValueAndValidity();
    }
  });
};


export class GenObject {
  dt: TypeDef.RequestParam;

  constructor(response: any[], label = "", value = "") {
    const params = {};
    const mapper = Object.keys(response[0]);
    label = label || mapper[0];
    value = value || mapper[1];
    Object.keys(response).forEach(key => {
      params[response[key][label]] = response[key][value];
    });
    this.dt = params;
  }
}
